<template>
  <view class="photo-form">
    <view class="form-header">
      <view class="header-title">{{ isEdit ? "编辑图片" : "查看图片" }}</view>
      <view v-if="!isEdit" class="edit-btn" @tap="toggleEdit">编辑</view>
    </view>

    <!-- 表单项 -->
    <!-- <view class="form-item">
      <view class="label">地址</view>
      <input
        class="input"
        type="text"
        placeholder="请填写地址"
        v-model="nameForm.name"
        :disabled="!isEdit"
      />
    </view> -->
    <view class="img-list">
      <view class="img-item" v-for="(item, index) in list" :key="index">
        <image :src="item" class="my-img" mode="widthFix" />
      </view>
      <empty v-if="list.length === 0" />


      <nut-button class="up-btn" type="primary" @tap="openPhoto" v-show="isEdit">
        <IconFont name="photograph" size="32" color="#fff" />
      </nut-button>
    </view>

    <!-- 保存按钮 -->
    <view v-if="isEdit" class="btn-wrapper">
      <nut-button class="save-btn" type="primary" @tap="saveName">保存</nut-button>
      <nut-button class="cancel-btn" @tap="toggleEdit">取消</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import http from "@/utils/http";
import { apiConfig } from "@/utils/config";
import { store } from "@/store/index";
import empty from "@/components/empty/index.vue";
import { IconFont } from "@nutui/icons-vue-taro";

// 直接解构store中的响应式状态
const { info, business } = store.storeState;
const shop = ref<any>(null)

const list = ref<any[]>([]);
// 获取页面参数
const router = Taro.getCurrentInstance().router;
const editType = ref(router?.params?.type || "view"); // 默认为查看模式
const isEdit = ref(editType.value === "edit"); // 根据传入的类型判断是否可编辑

// 设置导航栏标题
Taro.setNavigationBarTitle({
  title: isEdit.value ? "编辑图片" : "查看图片",
});

// 地址表单数据
const nameForm = ref({
  id: "",
  name: business.value.address,
});

// 状态变量
const uploadedImageUrl = ref('');
const uploading = ref(false);
const uploadError = ref('');

const openPhoto = async () => {
  uploadedImageUrl.value = ''; // 重置状态
  uploadError.value = ''; // 重置错误信息
  uploading.value = true; // 开始上传状态

  try {
    // 1. 选择图片
    const res = await Taro.chooseImage({
      count: 1, // 默认9，这里只允许选择一张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    });

    console.log('选择的图片:', res);


    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      const tempFilePath = res.tempFilePaths[0]; // 获取到选择的临时文件路径

      // 2. 上传图片
      const uploadRes = await Taro.uploadFile({
        url: apiConfig.baseURL + '/api/merchant/upload', // **替换成你的图片上传接口地址**
        filePath: tempFilePath,
        name: 'file', // 后端接收文件的字段名，通常是 'file' 或 'image'
        header: {
          'Content-Type': 'multipart/form-data',
          'Token': Taro.getStorageSync("token") // 如果需要认证，添加你的 token
        },
        formData: {
          // 如果需要传递额外的数据给后端，可以在这里添加
          'user_id': '123',
          'type': 'avatar'
        },
      });

      console.log('上传结果:', uploadRes);
      // if(uploadRes.code === 0) {
      //   Taro.showToast({ title: '上传成功', icon:'success' });
      // }
      // else{
      //   Taro.showToast({ title: '上传失败', icon:'none' });
      // }
      // return

      // 3. 处理上传结果
      if (uploadRes.statusCode === 200) {
        // 根据后端返回的数据结构解析，通常后端会返回图片的 URL
        const data = JSON.parse(uploadRes.data); // uploadRes.data 是一个字符串，需要解析
        if (data.code === 0 && data.data) { // 假设后端返回 { code: 0, msg: 'success', url: '...' }
          const uploadedImageUrl = apiConfig.baseURL + data.data;
          list.value.push(uploadedImageUrl);
          shop.value.imgUrl = uploadedImageUrl;
          Taro.showToast({ title: '上传成功', icon: 'success' });
        } else {
          throw new Error(data.msg || '上传失败，服务器返回错误');
        }
      } else {
        throw new Error(`上传失败，状态码：${uploadRes.statusCode}`);
      }
    }
  } catch (error) {
    console.error('上传图片失败:', error);
    uploadError.value = error.message || '未知错误';
    Taro.showToast({ title: '上传失败', icon: 'none' });
  } finally {
    uploading.value = false; // 结束上传状态
  }
};

// 切换编辑模式
function toggleEdit() {
  isEdit.value = !isEdit.value;
  if (!isEdit.value) {
    // 如果取消编辑，重新加载数据
    loadNameInfo();
  }
}

// 保存地址信息
function saveName() {

  Taro.showLoading({ title: "保存中..." });
  setTimeout(() => {
    Taro.hideLoading();
  }, 700);

  const param = { ...shop.value };
  delete param.balanceA;
  delete param.balanceB;
  delete param.id;
  http.postQuery("/api/merchant/update", param).then((res) => {
    console.log("res", res);
    if (res.code == 0) {
      Taro.showToast({ title: "保存成功", icon: "success" });
      Taro.navigateBack();
    }
    else {
      Taro.showToast({ title: '保存失败', icon: "none" });
    }
  });
}

onMounted(() => {
  // 加载地址信息
  loadNameInfo();
});


function loadNameInfo() {

  // 实际API调用示例
  http.post(`/api/merchant/getUserById`).then((res: any) => {
    console.log("res", res);
    if (res.code == 0 && res.data) {
      // nameForm.value = res.data;
      shop.value = res.data[0].columns;
      list.value = [shop.value.imgUrl]
    }
  });
}
</script>

<style lang="scss">
.photo-form {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;

  .up-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    margin: 20rpx auto;
    display: flex;
    justify-content: center;
    align-items: center;

    .nut-button__wrap {
      line-height: 100%;
    }
  }

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .edit-btn {
      padding: 10rpx 30rpx;
      background-color: #ff6034;
      color: #fff;
      border-radius: 30rpx;
      font-size: 28rpx;
    }
  }

  .form-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      font-weight: 500;
    }

    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1px solid #f5f5f5;
    }
  }

  .btn-wrapper {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding: 0 30rpx;
    margin-top: 40rpx;

    .save-btn {
      width: 100%;
    }

    .cancel-btn {
      width: 100%;
      background-color: #f5f5f5;
      color: #666;
    }
  }

  .img-list {
    width: 100%;

    .img-item {
      width: 100%;
      margin: 10rpx 0;

      .my-img {
        width: 100%;
        min-height: 120rpx;
        background: #eee;
      }
    }
  }
}
</style>
